//
//  NotificationViewController.swift
//  NotificationCentent
//
//  Created by hushaohua on 2019/1/25.
//  Copyright © 2019 init. All rights reserved.
//

import UIKit
import UserNotifications
import UserNotificationsUI

class NotificationViewController: UIViewController, UNNotificationContentExtension {

    @IBOutlet var label: UILabel?
    @IBOutlet weak var detailLabel: UILabel!
    
    var timer:Timer?;
    
    func startTimer() {
        self.stopTimer();
        self.timer = Timer(timeInterval: 1, target: self, selector: #selector(timeScheduled(_:)), userInfo: nil, repeats: true);
    }
    
    func stopTimer() {
        if (self.timer != nil){
            self.timer!.invalidate();
            self.timer = nil;
        }
    }
    
    @objc func timeScheduled(_ timer:Timer) {
        self.reloadLabel(Date());
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any required interface initialization here.
    }
    
    var notificationDate:Date?;
    
    func didReceive(_ notification: UNNotification) {
        self.startTimer();
        
        let userInfo = notification.request.content.userInfo;
        self.notificationDate = userInfo["date"] as? Date;
        
        self.reloadLabel(notification.date);
        
        self.detailLabel.text = notification.request.content.body;
    }
    
    func reloadLabel(_ date:Date) {
        if (self.notificationDate != nil){
            let interval = date.timeIntervalSince(self.notificationDate!);
            self.label?.text = "已经过去了\(interval)秒";
        }
    }

}
